package com.yuewen.mall.common.mongoclient;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by liwei.b on 2016/5/13.
 */
public class MongoDBClient {
    private static final int DefaultPort = 27017;
    private ServerAddress serverAddress;
    private MongoClient _instance = null;

    public MongoDBClient(ServerAddress serverAddress) {
        new MongoClient(serverAddress);
    }

    public MongoDBClient(ServerAddress serverAddress, String userName, String password) {
        List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
        mongoCredentials.add(MongoCredential.createCredential(userName, DatabaseNames.AdminDBName, password.toCharArray()));
        _instance = new MongoClient(serverAddress, mongoCredentials);
    }

    public MongoDBClient(List<ServerAddress> serverAddresses, String userName, String password) {
        List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
        mongoCredentials.add(MongoCredential.createCredential(userName,DatabaseNames.AdminDBName, password.toCharArray()));
        _instance = new MongoClient(serverAddresses, mongoCredentials);
    }

    //添加一个文档
    public void add(Object value, String databaseName, String collectioneName) {
        MongoDatabase db = _instance.getDatabase(databaseName);
        MongoCollection<Document> tmpCollections = db.getCollection(collectioneName);

        String key = _getKey();
        Document doc = new Document();
        doc.put(key, value);

        tmpCollections.insertOne(doc);
    }

    //查询满足条件的文档列表
    public <TResult> List<TResult> query(Document query, Class<TResult> objType, String databaseName, String collectioneName) {
        MongoDatabase db = _instance.getDatabase(databaseName);
        MongoCollection<Document> tmpCollections = db.getCollection(collectioneName);

        FindIterable<TResult> docuemts = null;
        try {
            docuemts = tmpCollections.find(query, objType);
        } finally {

        }
        List<TResult> tmpResults = new ArrayList<TResult>();
        if (docuemts != null) {
            MongoCursor<TResult> cursors = docuemts.iterator();
            while (cursors.hasNext()) {
                tmpResults.add(cursors.next());
            }
        }
        return tmpResults;
    }

    //删除一个文档
    public boolean delete(String id, String databaseName, String collectioneName) {
        MongoDatabase db = _instance.getDatabase(databaseName);
        MongoCollection<Document> tmpCollections = db.getCollection(collectioneName);
        DeleteResult deleteResult = null;
        try {
            ObjectId _id = new ObjectId(id);
            Bson filter = Filters.eq("_id", _id);
            deleteResult = tmpCollections.deleteOne(filter);
        } finally {

        }
        return (deleteResult != null && deleteResult.getDeletedCount() >= 1);
    }

    //更新一个文档
    public boolean update(String id, Document newValue, String databaseName, String collectioneName) {
        MongoDatabase db = _instance.getDatabase(databaseName);
        MongoCollection<Document> tmpCollections = db.getCollection(collectioneName);
        UpdateResult updateResult = null;
        try {
            ObjectId _id = new ObjectId(id);
            Bson filter = Filters.eq("_id", _id);
            updateResult = tmpCollections.updateOne(filter, newValue);
        } finally {

        }
        return (updateResult != null && updateResult.getModifiedCount() >= 1);
    }

    //关闭客户端链接
    public void close() {
        if (_instance != null) {
            _instance.close();
        }
    }

    private static String _getKey() {
        return UUID.randomUUID().toString();
    }
}
